package com.metagurukul.metaspace.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Ritesh gupta
 * This class is for create and close generic connection to database 
 * 
 */
public abstract class GenericConnection {
	
	/**
	 * initially take a connection variable con and set it to null
	 */
	private static Connection con = null;
	
	/**
	 *  to get connection
	 * @return Connection object con
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return con;
	}
	
	/** 
	 * to get a connection to the database
	 * 
	 * @param password  password of user database
	 * @param userId  userid of user database
	 * @param connectionString  connection string
	 * @param driver path of driver for database 
	 * @return connection  connection 
	 * @throws SQLException
	 */
	public static Connection generateConnection(String driver,
			String connectionString, String userId, String password)
			throws SQLException {
		try {
			/**
			 * load driver
			 */
			Class.forName(driver);
			/**
			 * call function to get connection
			 */
			con = DriverManager.getConnection(connectionString, userId,
					password);
		} catch (ClassNotFoundException e) {
			throw new SQLException("Driver Not Found");
		} catch (SQLException e) {
			throw new SQLException("Error In Database Connection"  + e);
		}
		/**
		 * return connection
		 */
		return con;
	}

	/**
	 * to close the database connection
	 * 
	 * @return true or false
	 * @throws SQLException
	 */
	public static boolean closeConnection() throws SQLException {
		if (con != null) {
			try {
				/**
				 * closing the connection
				 */
				con.close();
			} catch (SQLException e) {
				throw new SQLException("Error in Closing Connection"  + e);
			}
		}
		return true;	
	}
	
}
